package com.antler.smt.admin.service.impl;

import com.antler.smt.admin.mapper.*;
import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.OrderConstant;
import com.antler.smt.constant.PermissionConstant;
import com.antler.smt.entity.*;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.request.admin.EditOrderStatusReq;
import com.antler.smt.request.admin.OrderControllerReq;
import com.antler.smt.request.base.BasePageReq;
import com.antler.smt.request.portal.OrderLogisticsReq;
import com.antler.smt.response.admin.GetOrderCommentResp;
import com.antler.smt.response.admin.GetOrderLogisticsResp;
import com.antler.smt.response.admin.GetUserListResp;
import com.antler.smt.response.admin.OrderManageListResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.service.admin.ManageOrderService;
import com.antler.smt.utils.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *  获取订单管理列表
 *
 * @author zhangyi
 * @date 2018/4/28 11:08
 */
@Service
public class ManageOrderServiceImpl implements ManageOrderService {


    @Autowired
    private  ManageOrderInfoMapper manageOrderInfoMapper;

    @Autowired
    private RequirementEntityMapper requirementEntityMapper;

    @Autowired
    private MemberEntityMapper memberEntityMapper;

    @Autowired
    private SupplierEntityMapper supplierEntityMapper;

    @Autowired
    private PurchaserEntityMapper purchaserEntityMapper;

    @Autowired
    private OrderLogisticsInfoMapper orderLogisticsInfoMapper;

    @Autowired
    private OrderCommentInfoMapper orderCommentInfoMapper;

    @Autowired
    private OrderEntityMapper orderEntityMapper;

    @Autowired
    private ReceivingAddressEntityMapper receivingAddressEntityMapper;

    @Autowired
    private OrderLogisticsEntityMapper orderLogisticsEntityMapper;

    @Autowired
    private AttachmentEntityMapper attachmentEntityMapper;

    /**
     *  分类获取的订单列表
     *
     * @param orderStatus 订单状态列表
     * @param pageReq
     * @return
     */
    @Override
    public Result<PageInfo<OrderManageListResp>> getManageList(List<Integer> orderStatus,BasePageReq pageReq,Long userId) {
        Result result;
        PageHelper.startPage(pageReq.getPageCurrent(), pageReq.getPageSize());
        PageHelper.orderBy("order_time DESC");
        OrderControllerReq orderControllerReq = new OrderControllerReq();
        orderControllerReq.setStatus(orderStatus);

        if(PermissionConstant.SUPER_ADMIN.equals(userId)){
            orderControllerReq.setUserId(null);
        }else{
            orderControllerReq.setUserId(userId);
        }

        Page<OrderManageListResp> listManageOrder  =
                manageOrderInfoMapper.getManageOrderList(orderControllerReq);

        if (listManageOrder != null) {
            PageInfo<GetUserListResp> listOrderManagePageInfo = new PageInfo(listManageOrder);
            result = new Result(listOrderManagePageInfo);
        } else {
            result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "获取管理订单所有列表数据为空！");
        }
        return result;
    }

    /**
     * 获取服务商的昵称
     *
     * @param supplierId
     * @return
     */
    @Override
    public Result<String> getSupplierMemberInfo(Long supplierId) {
        Result result = null;

        //获取服务商实体
        SupplierEntity supplierEntity = supplierEntityMapper.selectByPrimaryKey(supplierId);

        //获取此服务商的会员实体
        MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(supplierEntity.getMemberId());

        //获取昵称
        result = new Result(memberEntity.getNickName());

        return result;
    }

    /**
     * 获取采购商的会员信息
     *
     * @param purchaserId
     * @return
     */
    @Override
    public Result<MemberEntity> getPurchaserInfo(Long purchaserId) {
        Result result = null;

        //获取采购商实体
        PurchaserEntity purchaserEntity = purchaserEntityMapper.selectByPrimaryKey(purchaserId);

        //获取采购商会员信息
        MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(purchaserEntity.getMemberId());

        result = new Result(memberEntity);
        return result;
    }

    /**
     *  获取服务商的详细信息
     *
     * @param supplierId
     * @return
     */
    @Override
    public Result<SupplierEntity> getSupplierInfo(Long supplierId) {
        return new Result<>(supplierEntityMapper.selectByPrimaryKey(supplierId));
    }


    /**
     *  获取发布需求详细信息
     *
     * @param requirementId
     * @return
     */
    @Override
    public Result<RequirementEntity> orderManageRequirement(Long requirementId) {
        Result result = null;
        result = new Result(requirementEntityMapper.selectByPrimaryKey(requirementId));
        return result;
    }

    /**
     * 获取订单的物流信息
     *
     * @param orderId
     * @return
     */
    @Override
    public Result<OrderLogisticsEntity> orderManageLogistics(Long orderId) {
        Result result = null;
        GetOrderLogisticsResp getOrderLogisticsResp = orderLogisticsInfoMapper.selectOrderLogisticsInfo(orderId);
        result = new Result(getOrderLogisticsResp);
        return result;
    }

    /**
     *  获取订单的评价信息
     *
     * @param orderId
     * @return
     */
    @Override
    public Result<OrderCommentEntity> orderManagecomment(Long orderId) {
        Result result = null;
        GetOrderCommentResp orderComment = orderCommentInfoMapper.getOrderComment(orderId);
        result = new Result(orderComment);
        return result;
    }

    /**
     * 获取订单的详细信息
     *
     * @param orderId
     * @return
     */
    @Override
    public Result orderManageInfo(Long orderId) {
        Result result = null;
        //获取订单详情
        OrderEntity orderEntity = orderEntityMapper.selectByPrimaryKey(orderId);
        AttachmentEntity attachmentEntity = attachmentEntityMapper.selectByPrimaryKey(orderEntity.getTestReportAttachmentId());
        if(attachmentEntity != null){
            orderEntity.setReportName(attachmentEntity.getFileName());
        }
        //获取采购商发布需求实体
        RequirementEntity requirementEntity =
                requirementEntityMapper.selectByPrimaryKey(orderEntity.getRequirementId());
        //获取采购商实体
        PurchaserEntity purchaserEntity =
                purchaserEntityMapper.selectByPrimaryKey(requirementEntity.getPurchaserId());
        //获取收货地址信息
        ReceivingAddressEntity receivingAddressEntity =
                receivingAddressEntityMapper.selectByPrimaryKey(requirementEntity.getAddressId());
        List<Object> list = new ArrayList<>();
        list.add(orderEntity);
        list.add(receivingAddressEntity);
        list.add(purchaserEntity);
        result = new Result(list);
        return result;
    }

    /**
     * 项目专员代发货
     *
     * @param orderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> userTakeSend(Long orderId,OrderLogisticsReq request) {
        Result result = null;

        //创建订单实体
        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setId(orderId);

        //更新时间
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //进度 0待对接服务商 1待付款 2待确认付款 3待生产完成  4待收货 6待评价 7待付款给服务商 8结束 100驳回
        orderEntity.setStatus(OrderConstant.ORDER_WAIT_GIVEGOODS);

        //发货：订单状态改变
        int orderCount = orderEntityMapper.updateByPrimaryKeySelective(orderEntity);

        //创建快递物流实体
        OrderLogisticsEntity orderLogisticsEntity = new OrderLogisticsEntity();

        //添加快递运单号
        orderLogisticsEntity.setOrderId(orderId);

        //添加快递公司id
        orderLogisticsEntity.setPostCompanyId(request.getPostCompanyId());

        //添加快递方式(自提，快递)
        orderLogisticsEntity.setPostType(request.getPostType());

        //添加快递
        orderLogisticsEntity.setPostCompanyName(request.getPostCompanyName());

        //添加运单号
        orderLogisticsEntity.setTrackingNo(request.getTrackingNo());

        //添加发货方式
        orderLogisticsEntity.setDeliverType(Byte.parseByte("2"));

        //添加时间
        orderLogisticsEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
        orderLogisticsEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int orderLogisticsCount = orderLogisticsEntityMapper.insertSelective(orderLogisticsEntity);

        if(0 == (orderCount & orderLogisticsCount)){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }

        return result;
    }

    /**
     * 修改订单状态（给采购商发票，服务商给我们发票，和采购商签合同，服务商和我们签合同，来料验收，领料验收）
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> editStatus(EditOrderStatusReq request) {
        Result result = null;
        int i = manageOrderInfoMapper.updateOrderOtherStatus(request);
        result = (0 == i?new Result(ResultCodeEnum.APPEND_DATA_ERROR):new Result(ResultCodeEnum.OPERATION_SUCCESS));
        return result;
    }
}
